//
//  SelectImgUtils.m
//  laowu
//
//  Created by 尹桥印 on 15/5/10.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//

#import "SelectImgUtils.h"
#import "JTSActionSheet.h"
#import "UpYun.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "ZYQAssetPickerController.h"

static SelectImgUtils *instance;
@interface SelectImgUtils()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,ZYQAssetPickerControllerDelegate>
@property (nonatomic,strong)UIImagePickerController *imagePickerController;
@property (strong, nonatomic) UIViewController *currentCtrl;

@end

@implementation SelectImgUtils

+(instancetype)shareInstance{
    if (!instance) {
        instance = [[SelectImgUtils alloc] init];
    }
    return instance;
}

-(void)selectImageWithCtrl:(UIViewController *)ctrl{
    _currentCtrl = ctrl;
    /*
    JTSActionSheetTheme *theme = [JTSActionSheetTheme defaultTheme];
    theme.separatorColor = HEXColor(@"#dfdfdf");
    theme.normalButtonColor = [UIColor blackColor];
    theme.destructiveButtonColor = [UIColor blackColor];
    theme.titleColor = [UIColor blackColor];
    JTSActionSheetItem *buyAll = [JTSActionSheetItem itemWithTitle:@"拍照" action:^{
        //前往拍照
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
        //设置拍照时的下方的工具栏是否显示，如果需要自定义拍摄界面，则可把该工具栏隐藏
        _imagePickerController.showsCameraControls  = YES;
        [ctrl.navigationController.viewControllers.lastObject.navigationController.viewControllers.lastObject presentViewController:_imagePickerController animated:YES completion:nil];
    } isDestructive:NO];
    
    JTSActionSheetItem *deleteAll = [JTSActionSheetItem itemWithTitle:@"从手机相册选择" action:^{
        //前往手机相册
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
        [ctrl.navigationController.viewControllers.lastObject presentViewController:_imagePickerController animated:YES completion:nil];
    } isDestructive:NO];
    
    JTSActionSheetItem *cancel = [JTSActionSheetItem itemWithTitle:@"取消" action:^{
    } isDestructive:NO];
    
    JTSActionSheet *sheet = [[JTSActionSheet alloc] initWithTheme:theme
                                                            title:nil
                                                      actionItems:@[buyAll, deleteAll]
                                                       cancelItem:cancel];
    [sheet showInView:ctrl.view];
     
     */
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从手机相册选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:ctrl.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {//拍照
        //前往拍照
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
        //设置拍照时的下方的工具栏是否显示，如果需要自定义拍摄界面，则可把该工具栏隐藏
        _imagePickerController.showsCameraControls  = YES;
        [_currentCtrl.navigationController presentViewController:_imagePickerController animated:YES completion:nil];

    }else if(buttonIndex == 1) {//相册
        //前往手机相册
        ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
        picker.view.width = SCREENW;
        picker.maximumNumberOfSelection = _maxSelectCount;
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups=NO;
        picker.delegate=self;
        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 5;
            } else {
                return YES;
            }
        }];
        
        [_currentCtrl.navigationController presentViewController:picker animated:YES completion:nil];
    }else if(buttonIndex == 2) {//取消
       
    }
    [actionSheet dismissWithClickedButtonIndex:buttonIndex animated:YES];
}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet{
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取图片裁剪的图
    UIImage* edit = [info objectForKey:UIImagePickerControllerEditedImage];
    [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
    if ([_delegate respondsToSelector:@selector(selectImgUtilsImg:)]) {
        [_delegate selectImgUtilsImg:edit];
    }
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    __block float fileKB  = 0.0;
    double perMBBytes = 1024.0;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 处理耗时操作的代码块...
        for (int i=0; i<assets.count; i++) {
            ALAsset *asset=assets[i];
            //计算image的大小(kb)
            ALAssetRepresentation *representation = [asset defaultRepresentation];
            fileKB = (double)([representation size]/perMBBytes);
            NSLog(@"size of asset in bytes: %0.2f kb", fileKB);
            UIImage *tempImg = nil;
            if (fileKB>300) {
                //需要压缩
                //                NSData *data = UIImageJPEGRepresentation([UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage], 0.75);
                //                tempImg = [UIImage imageWithData:data];
                tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            }else{
                tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新
                if ([_delegate respondsToSelector:@selector(selectImgUtilsImg:)]) {
                    [_delegate selectImgUtilsImg:tempImg];
                }
            });
        }
    });
}

@end
